<template>
  <view class="max_box">
    <canvas class="canvas-img" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" canvas-id="firstCanvas"
      id="firstCanvas" @longpress="canvasGet"></canvas>

    <!-- 以下是html的海报 -->
    <viwe class="preview_box">
      <view class="box" :class="{ preview_box_667: windowHeight <= 700 }">
        <image class="img-bg" mode="widthFix" src="https://www.kamlung.net/images/other/bg-600x1095.jpg" />
        <!-- <view class="img_box" :style="{ 'background-image': `url(${canvasInfo.imageHead})` }"></view> -->
        <view class="img_box">
          <image class="img" mode="aspectFill" :src="canvasInfo.imageHead" />
        </view>
        <view class="text">
          <view class="name title">{{ canvasInfo.textHead }}</view>
          <view class="name">扫码即刻查看车辆信息</view>
          <view class="user">
            <view class="img-text">
              <image mode="widthFix" :src="canvasInfo.headImg" />
            </view>
            <view class="name">{{ canvasInfo.titleRank }}</view>
          </view>
          <view class="qs">
            <image mode="widthFix" :src="canvasInfo.imageBody" />
          </view>
        </view>
      </view>
    </viwe>

    <view class="save_btn_box">
      <view class="save_btn" @click.stop="saveImage">保存车辆信息</view>
    </view>
  </view>
</template>
<script>
import { getImageInfo } from "@/utils/canvasFn.js";
export default {
  name: "PosterCanvas",
  data() {
    return {
      canvasPath: "",
      context: null,
      canvasWidth: 600, //图片宽度
      canvasHeight: 1095, //图片高度
      windowHeight: "",
    };
  },
  props: {
    // 背景
    imageBg: {
      type: String,
      default: "https://www.kamlung.net/images/other/bg-600x1095.jpg",
    },
    myCanvasSize: {
      type: Array,
      default() {
        return [0.8, 16 / 9]; //[0]为画布占屏幕宽度的比例，[1]为背景画布长宽比
      }
    },
    canvasInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      uni.showLoading({
        title: "生成海报中...",
      });
      let ctx = uni.createCanvasContext("firstCanvas", this);
      let {
        imageHead,
        textHead,
        imageBody,
        headImg,
        titleRank
      } = this.canvasInfo
      // 背景
      let imageBgUrl = await getImageInfo(this.imageBg);
      ctx.drawImage(imageBgUrl.path, 0, 0, this.canvasWidth, this.canvasHeight);
      // 海报
      let imgHead = await getImageInfo(imageHead);
      ctx.drawImage(imgHead.path, this.canvasWidth * 0.5 - 270, 30, 540, 680);
      // 头像
      let headUrl = await getImageInfo(headImg);
      this.drawRoundImg(
        ctx,
        headUrl.path,
        30,
        850,
        90,
        90,
        45 // 圆角
      );
      // 二维码
      console.log("二维码", imageBody);
      let imgBody = await getImageInfo(imageBody);
      ctx.drawImage(imgBody.path, 410, 800, 160, 160);

      // 大标题
      ctx.font = "normal bold 26px Microsoft JhengHei";
      ctx.textAlign = "left";
      ctx.setFontSize(30);
      ctx.setTextBaseline("middle");
      ctx.setFillStyle("#222");
      ctx.fillText(textHead, 30, 756);
      // 副标题
      ctx.font = "normal bold 22px Microsoft JhengHei";
      ctx.setFontSize("24");
      ctx.setTextBaseline("middle");
      ctx.setFillStyle("#666");
      ctx.fillText("扫码即刻查看车辆信息", 30, 810);
      // 姓名
      ctx.font = "normal bold 14px Microsoft JhengHei";
      // ctx.font = 'normal 400 18px Microsoft JhengHei'
      ctx.setFontSize("24");
      ctx.setTextBaseline("middle");
      ctx.setFillStyle("#222");
      ctx.fillText(titleRank, 140, 895);
      ctx.draw();
      uni.hideLoading();
      this.canvasGet();
    },

    // 生成临时图片地址
    canvasGet() {
      // var that = this
      uni.canvasToTempFilePath(
        {
          canvasId: "firstCanvas",
          success: (res) => {
            // 在H5平台下，tempFilePath 为 base64
            console.log("地址", res.tempFilePath);
            // this.canvasPath = ''
            this.canvasPath = res.tempFilePath;
            // console.log('',res.tempFilePath);
          },
          fail: () => {
            console.log("下载失败");
          },
        },
        this
      );
    },
    //带圆角图片
    drawRoundImg(ctx, img, x, y, width, height, radius) {
      ctx.beginPath();
      ctx.setStrokeStyle("#ccc");
      ctx.save();
      // 左上角
      ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5);
      // 右上角
      ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2);
      // 右下角
      ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5);
      // 左下角
      ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI);
      ctx.stroke();
      ctx.clip();
      ctx.drawImage(img, x, y, width, height);
      ctx.restore();
      ctx.closePath();
    },
    //保存图片到相册
    saveImage() {
      //获取用户的当前设置。获取相册权限
      uni.getSetting({
        success: (res) => {
          //如果没有相册权限
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            //向用户发起授权请求
            uni.authorize({
              scope: "scope.writePhotosAlbum",
              success: () => {
                //授权成功后，保存图片到系统相册
                uni.canvasToTempFilePath(
                  {
                    canvasId: "firstCanvas",
                    quality: 1,
                    fileType: "jpg",
                    complete: (res) => {
                      console.log("保存到相册", res);
                      uni.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success(res) {
                          // uni.showToast({
                          //   title: '已保存到相册',
                          //   icon: 'success',
                          //   duration: 2000,
                          // })
                          uni.showModal({
                            title: "提示",
                            showCancel: false,
                            content: "图片已保存到相册，快去分享到朋友圈吧",
                            success: function (res) { },
                          });
                        },
                      });
                    },
                  },
                  this
                );
              },
              //授权失败
              fail: () => {
                // uni.hideLoading()
                uni.showModal({
                  title: "您拒绝了获取相册权限。",
                  content: "进入权限管理,授权相册权限,保存图片。",
                  success: (res) => {
                    if (res.confirm) {
                      //调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
                      uni.openSetting({
                        success: (res) => {
                          console.log(res.authSetting);
                        },
                      });
                    } else if (res.cancel) {
                      return uni.showToast({
                        title: "已取消！",
                      });
                    }
                  },
                });
              },
            });
          } else {
            //如果已有相册权限，直接保存图片到系统相册
            uni.canvasToTempFilePath(
              {
                canvasId: "firstCanvas",
                quality: 1,
                fileType: "jpg",
                complete: (res) => {
                  console.log("保存到相册", res);
                  uni.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success(res) {
                      uni.showModal({
                        title: "提示",
                        showCancel: false,
                        content: "图片已保存到相册，快去分享到朋友圈吧",
                        success: function (res) { },
                      });
                      // uni.showToast({
                      //   title: '已保存到相册',
                      //   icon: 'success',
                      //   duration: 2000,
                      // })
                    },
                  });
                },
              },
              this
            );
          }
        },
        fail: (res) => { },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.canvas-img {
  // margin-left: 10px;
  position: absolute;
  left: -1800rpx;
}

.max_box {
  height: 100%;

  // background-color: #222222;
  .preview_box {
    z-index: 2;

    .box {
      width: 640rpx;
      height: 1260rpx;
      overflow: hidden;
      margin: 30rpx auto 0;
      position: relative;
      box-shadow: 0px 0px 10px 0px rgba(5, 5, 5, 0.25);

      .img-bg {
        width: 100%;
        height: 100%;
        // box-shadow: 0px 0px 10px 0px rgba(5, 5, 5, 0.25);
      }

      .img_box {
        width: calc(100% - 80rpx) !important;
        height: 720rpx;
        position: absolute;
        top: 40rpx;
        left: 40rpx;
        background-size: cover;
        background-repeat: no-repeat;
        overflow: hidden;
        // border: 1px solid #f00;
        .img {
          // margin-top: -40px;
          height: 100%;
        }
      }
    }

    .text {
      position: absolute;
      top: 770rpx;
      left: 40rpx;
      margin-left: 0;
      width: calc(100% - 80rpx) !important;
      text-align: left;
      color: #222;

      .title {
        font-size: 36rpx !important;
        font-weight: 600;
        margin-bottom: 10rpx !important;
      }

      .name {
        font-size: 30rpx;
        width: 100%;
        margin-bottom: 20rpx;
        display: block;
      }

      .user {
        position: relative;

        .img-text {
          position: absolute;
          top: 0;
          left: 0;
          width: 100rpx;
          height: 100rpx;
          border-radius: 50%;
          border: 2rpx solid rgba(0, 0, 0, 0.1);
          overflow: hidden;
        }

        .name {
          width: 200rpx;
          height: 100rpx;
          line-height: 100rpx;
          margin-left: 130rpx;
        }
      }

      .qs {
        position: absolute;
        width: 190rpx;
        height: 190rpx;
        bottom: -12px;
        right: -10px;
      }
    }
  }

  .preview_box_667 {
    position: relative !important;
    height: 1434rpx !important;
  }

  // 按钮
  .save_btn_box {
    padding: 20rpx 0 40rpx 0;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    box-shadow: 0px 0px 10px 0px rgba(5, 5, 5, 0.25);

    .save_btn {
      width: 660rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 30rpx;
      border-radius: 0;
      background-color: #111;
      margin: 20rpx auto 50rpx auto;
      text-align: center;
      color: #ffffff;
      background-color: #000;
    }
  }
}
</style>
